package edu.fdzc.project.common;

//import cn.hutool.json.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import edu.fdzc.project.utils.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.PrintWriter;

public class Interceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String thoken = request.getHeader("Authorization");

        if(thoken==null || JwtUtil.parseToken(thoken) == null){
            response.setStatus(401);
            response.setContentType("application/json:charset=utf-8");
            Result<Object> result = Result.error(Code.UNAUTHORIZED,"请重新登录");

            try (PrintWriter out = response.getWriter()) {
                // 使用ObjectMapper将Result对象序列化为JSON字符串
                ObjectMapper objectMapper = new ObjectMapper();
                // 将JSON字符串写入响应输出流，发送给客户端
                out.write(objectMapper.writeValueAsString(result));
            }

            return false;
        }
        return true;

    }

}
